package com.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author robin
 * @Date 2021/11/18
 * @Description
 */
public class RobinApplicationContext {
    private Class configClass;
    private Map<String, BeanDefiniton> beanDefinitonMap = new HashMap<>();
    private Map<String, Object> singletonObjects = new HashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public RobinApplicationContext(Class configClass) {
        this.configClass = configClass;
        scan(configClass);
        for (Map.Entry<String, BeanDefiniton> entry : beanDefinitonMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefiniton beanDefiniton = entry.getValue();
            if (beanDefiniton.getScope().equals("singleton")) {

            }
        }


    }

    private Object createBean(String beanName, BeanDefiniton beanDefiniton) {
        Class type = beanDefiniton.getType();
        Object instance = null;
        try {
            instance = type.getConstructor().newInstance();
            for (Field field : type.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(beanName));
                }
            }
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessorBeforeInitialization(instance, beanName);
            }
            if (instance instanceof InitializationBean) {
                ((InitializationBean) instance).afterPropertiesSet();
            }
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessorAfterInitialization(instance, beanName);
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return instance;
    }

    private Object getBean(String beanName) {
        if (!beanDefinitonMap.containsKey(beanName)) {
            throw new NullPointerException();
        }
        BeanDefiniton beanDefiniton = beanDefinitonMap.get(beanName);
        if (beanDefiniton.getScope().equals("singleton")) {
            Object singletonBean = singletonObjects.get(beanName);
            if (singletonBean == null) {
                singletonBean = createBean(beanName, beanDefiniton);
                singletonObjects.put(beanName, singletonBean);
            }
            return singletonBean;
        } else {
            Object protoTypeBean = createBean(beanName, beanDefiniton);
            return protoTypeBean;
        }

    }

    private void scan(Class configClass) {
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScan = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScan.value();
            path = path.replace(".", "/");
            ClassLoader classLoader = RobinApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());
            if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    String absolutePath = f.getAbsolutePath();
                    absolutePath = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
                    absolutePath = absolutePath.replace("\\", ".");
                    try {
                        Class<?> aClass = classLoader.loadClass(absolutePath);
                        if (aClass.isAnnotationPresent(ComponentScan.class)) {
                            if (BeanPostProcessor.class.isAssignableFrom(aClass)) {
                                BeanPostProcessor beanPostProcessor = (BeanPostProcessor) aClass.getConstructor().newInstance();
                                beanPostProcessorList.add(beanPostProcessor);
                            }
                            Component component = aClass.getAnnotation(Component.class);
                            String beanName = component.value();
                            if ("".equals(beanName)) {
                                beanName = Introspector.decapitalize(aClass.getSimpleName());
                            }
                            BeanDefiniton beanDefiniton = new BeanDefiniton();
                            beanDefiniton.setType(aClass);
                            if (aClass.isAnnotationPresent(Scope.class)) {
                                Scope scope = aClass.getAnnotation(Scope.class);
                                String value = scope.value();
                                beanDefiniton.setScope(value);
                            } else {
                                beanDefiniton.setScope("singleton");
                            }
                            beanDefinitonMap.put(beanName, beanDefiniton);

                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }
}
